package cn.netuo.bumbersoll.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.rooten.util.Util;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.tencent.bugly.beta.interfaces.BetaPatchListener;
import com.tencent.bugly.beta.ui.UILifecycleListener;
import com.tencent.bugly.beta.upgrade.UpgradeListener;
import com.tencent.bugly.beta.upgrade.UpgradeStateListener;
import com.tencent.tinker.lib.tinker.Tinker;

import java.io.File;
import java.util.Locale;

import cn.netuo.bumbersoll.App;
import cn.netuo.bumbersoll.BuildConfig;
import lib.grasp.util.AppUtil;
import lib.grasp.util.FileUtil;
import lib.grasp.util.L;

/**
 * Created by JS_grasp on 2019/3/18.
 */
public class BuglyUtil {

    static String argPath = "";
    static String apkPath = "";

    public static void initBugly(){
        /* ------------------[重要]如果是发布版请改为Bugly正式版本----------------------------------- */

        // 设置开发设备，默认为false，上传补丁如果下发范围指定为“开发设备”，需要调用此接口来标识开发设备

        boolean isDevelopDev = BsUtil.getBuglyIsDevelopDev(App.getApp());
        Bugly.setIsDevelopmentDevice(App.getApp(), isDevelopDev);

        setStrictMode();

        if(Build.VERSION.SDK_INT == 23){                        // 6.0
            Beta.storageDir = App.getApp().getExternalFilesDir(null);
            argPath = "/apk/";
        }
        else if(Build.VERSION.SDK_INT <= 22){                   // 6.0一下
            Beta.storageDir = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/");
            argPath = "/" + App.getApp().getPackageName() + "/.beta/apk/";
        }

        Beta.enableHotfix = true;           // 设置是否开启热更新能力，默认为true
        Beta.canAutoDownloadPatch = true;   // 设置是否自动下载补丁，默认为true
        Beta.canNotifyUserRestart = false;  // 设置是否提示用户重启，默认为false
        Beta.canAutoPatch = true;           // 设置是否自动合成补丁，默认为true

        Beta.autoDownloadOn4g = true;
        Beta.enableNotification = true;
        Beta.autoDownloadOnWifi = true;
        Beta.autoInstallApk = true;

        // 补丁回调接口，可以监听补丁接收、下载、合成的回调
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String patchFile) {
                L.logOnly("-----------onPatchReceived--补丁下载地址--------------:");
            }

            @Override
            public void onDownloadReceived(long savedLength, long totalLength) {
                String rate = String.format(Locale.getDefault(), "%s %d%%", Beta.strNotificationDownloading, (int) (totalLength == 0 ? 0 : savedLength * 100 / totalLength));
                L.logOnly("-----------onDownloadReceived----------------:" + rate);
            }

            @Override
            public void onDownloadSuccess(String msg) {
                L.logOnly("-----------补丁下载成功--------------:" + msg);
            }

            @Override
            public void onDownloadFailure(String msg) {
                L.logOnly("-----------补丁下载失败--------------:" + msg);

            }

            @Override
            public void onApplySuccess(String msg) {
                L.logOnly("-----------补丁应用成功------------:" + msg);

                System.exit(1);
                android.os.Process.killProcess(android.os.Process.myPid());
            }

            @Override
            public void onApplyFailure(String msg) {
                L.logOnly("-----------补丁应用失败------------:" + msg);
            }

            @Override
            public void onPatchRollback() {
                L.logOnly("-----------补丁回滚------------");
            }
        };


        // 全量升级状态回调
        Beta.upgradeStateListener = new UpgradeStateListener() {
            @Override
            public void onUpgradeFailed(boolean b) {
                L.logOnly("-----------onUpgradeFailed----------------:" + b);
            }

            @Override
            public void onUpgradeSuccess(boolean b) {
                L.logOnly("-----------onUpgradeSuccess----------------:" + b);
            }

            @Override
            public void onUpgradeNoVersion(boolean b) {
                L.logOnly("-----------onUpgradeNoVersion----------------:" + b);
            }

            @Override
            public void onUpgrading(boolean b) {
                L.logOnly("-----------onUpgrading----------------:" + b);
            }

            @Override
            public void onDownloadCompleted(boolean b) {
                L.logOnly("-----------onDownloadCompleted----------------:" + b);
                if(TextUtils.isEmpty(apkPath)) return;
                onSmartInstall(App.getApp(), apkPath);
                apkPath = "";
            }
        };

        Beta.upgradeDialogLifecycleListener = new UILifecycleListener<UpgradeInfo>() {
            @Override
            public void onCreate(Context context, View view, UpgradeInfo upgradeInfo) {
                System.out.println("onCreate");
            }

            @Override
            public void onStart(Context context, View view, UpgradeInfo upgradeInfo) {
                System.out.println("onStart");
            }

            @Override
            public void onResume(Context context, View view, UpgradeInfo upgradeInfo) {
                L.logOnly("onResume:" + upgradeInfo.fileSize);
                L.logOnly("onResume:" + upgradeInfo.apkUrl);
                L.logOnly("onResume:" + upgradeInfo.title);
                L.logOnly("onResume:" + upgradeInfo.versionName + "." + upgradeInfo.versionCode);

                File file = new File(upgradeInfo.apkUrl);
                String fileName = file.getName();
                file = new File(Beta.storageDir + argPath, fileName);
                System.out.println("1-----file.getAbsolutePath():" + file.getAbsolutePath());
                if(!file.exists() || file.isDirectory()) {
                    L.logOnly("文件不存在或者文件异常");
                    return;
                }
                L.logOnly("文件存在");
                L.logOnly("md5-网络:" + upgradeInfo.apkMd5);
                L.logOnly("md5-本地:" + FileUtil.getFileMD5(file));
                L.logOnly("文件大小-网络:" + upgradeInfo.fileSize);
                L.logOnly("文件大小-本地:" + file.length());
                apkPath = file.getAbsolutePath();

                if(TextUtils.equals(upgradeInfo.apkMd5, FileUtil.getFileMD5(file))){
                    onSmartInstall(context, file.getAbsolutePath());
                    apkPath = "";
                }

                // 发广播(please.install)
//                Intent intent = new Intent();
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.setAction("please.install");
//                intent.putExtra("apkpath", file.getAbsolutePath());
//                App.getApp().sendBroadcast(intent);

//                onSmartInstall(file.getAbsolutePath());

                // 听广播(grasp.arg.loop)

            }

            @Override
            public void onPause(Context context, View view, UpgradeInfo upgradeInfo) {
                System.out.println("onPause");
            }

            @Override
            public void onStop(Context context, View view, UpgradeInfo upgradeInfo) {
                System.out.println("onStop");
            }

            @Override
            public void onDestroy(Context context, View view, UpgradeInfo upgradeInfo) {
                System.out.println("onDestroy");
            }
        };

        Bugly.setUserId(App.getApp(), "123546");
        Bugly.setUserTag(App.getApp(), Build.VERSION.SDK_INT);
//        Bugly.putUserData(App.getApp(), "key1", "123");
        Bugly.setAppChannel(App.getApp(), "tys-pad");

        // 这里实现SDK初始化，
        // appId替换成你的在Bugly平台申请的appId,
        // 调试时将第三个参数设置为true
        boolean enableLog = BsUtil.getBuglyEnableLog(App.getApp());
        Bugly.init(App.getApp(), "42088c247e", enableLog);
    }


    @TargetApi(9)
    private static void setStrictMode() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }

    public static void onSmartInstall(Context context, String apkPath) {
        if (TextUtils.isEmpty(apkPath)) {
            L.logOnly("安装包不存在");
            return;
        }
        if(AppUtil.isRoot()){   // 优先静默安装
            AppUtil.installSilence(context, apkPath);
        }
        else{
            Uri uri = Uri.fromFile(new File(apkPath));
            Intent localIntent = new Intent(Intent.ACTION_VIEW);
            localIntent.setDataAndType(uri, "application/vnd.android.package-archive");
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            App.getApp().startActivity(localIntent);
        }

    }
}
